# -*- coding: utf-8 -*-
# @时间：2023/11/2 20:25
# @作者：CJiaの可乐哥
# @文件名：cj_auth
# @软件：Pycharm2023
import jwt
from datetime import datetime

from ninja.security import HttpBearer
from django.core.cache import cache
from system.models import Users, UserRole, RolePermission
from utils.cj_jwt import parse_payload
from utils.cj_response import ErrorResponse


class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        token = request.META.get("HTTP_AUTHORIZATION")
        token = token.replace('Bearer ', "")
        result = parse_payload(token)
        code = result['code']
        if code == 0:
            data = result['data']
            redis_token = cache.get(data['username'] + str(data['key']))
            if redis_token:
                request.username = data['username']
                return token
            else:
                raise TimeoutError(401, "token已失效")
        else:
            raise TimeoutError(401, result['msg'])


def authenticate(func):
    """
    权限认证装饰器
    :param func:
    :return:
    """

    def wrapper(request, *args, **kwargs):
        user = Users.objects.get(username=request.username)
        # print(request.types)
        if user.is_superuser == 2:
            role_id = UserRole.objects.get(user_id=user.id).role_id
            delete = RolePermission.objects.filter(role_id=role_id, permission__in=request.types).exists()
            if not delete:
                return ErrorResponse(msg="演示环境，暂不可操作")
        return func(request, *args, **kwargs)

    return wrapper
